package services;

import dto.Language;
import models.Constants;
import models.Menu;
import play.Logger;
import play.cache.Cache;
import play.i18n.Lang;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by Gipxy group
 * Date: 4/2/12
 */
public class MenuService {

    public static List[] getProductMenuItems() {
        System.out.println("getProductMenuItems.Size:="+getMenuItems(Constants.PRODUCT_MENU_KEY).length);
        return getMenuItems(Constants.PRODUCT_MENU_KEY);
    }

    public static List[] getAppMenuItems() {
        //System.out.println("getAppMenuItems.Size:="+getMenuItems(Constants.APP_MENU_KEY).length);
        return getMenuItems(Constants.APP_MENU_KEY);
    }

    private static void updateCache(String belongTo, String lang) {
        String cacheKey = "menu." + belongTo+ "." + lang;
        List[] p = getMenuItemsFromDB(belongTo, lang);
        Cache.set(cacheKey, p, Constants.UNLIMIT_TIME);
    }


    public static void updateCache() {
        Logger.debug("Do update Menu cache!");

        Language[] langs = Language.all;
        String[] belongTos = new String[] {Constants.PRODUCT_MENU_KEY, Constants.APP_MENU_KEY};

        for (Language lang : langs) {
            for(String belongTo : belongTos) {
                updateCache(belongTo, lang.code);
            }
        }
    }

    private static List[] getMenuItems(String belongTo) {
        String cacheKey = "menu." + belongTo+ "." + Lang.get();
        //check in cache first

        if (Cache.get(cacheKey)==null) {
            List[] p = getMenuItemsFromDB(belongTo, Lang.get());
            Cache.set(cacheKey, p, Constants.UNLIMIT_TIME);
        }

        return (List[]) Cache.get(cacheKey);
    }

    private static List[] getMenuItemsFromDB(String belongTo, String lang) {
        List[] p = new ArrayList[2];

        List<Menu> all = Menu.all(Menu.class).filter(Language.LANGUAGE_KEY, lang).fetch();
        for(Menu m : all) {
            if (p[m.getColumn()-1]==null) {
                p[m.getColumn()-1] = new ArrayList();
            }

            p[m.getColumn()-1].add(m);
        }

        sortMenu(p[0]);
        sortMenu(p[1]);
        return p;
    }

    private static void sortMenu(List<Menu> menus) {
        if (menus==null) return;
        Collections.sort(menus, new Comparator<Menu>() {
            @Override
            public int compare(Menu o1, Menu o2) {
                return ((Integer)o1.getIndex()).compareTo(o2.getIndex());
            }
        });
    }
}
